import pandas as pd
import pdfplumber
import os
from pathlib import Path


class FileHanding:

    @staticmethod
    def dataframe_handler(df: pd.DataFrame):
        # df = df.dropna(axis=0)
        df = df.replace('\n', '', regex=True)
        # df = df.applymap(lambda x: str(x).strip())
        return df
    
    @staticmethod    
    def read_pdf(file_path:str):
        file_path = Path(file_path)
        data = pd.DataFrame()
        with pdfplumber.open(file_path) as pdf:
            for page_number, page in enumerate(pdf.pages, start=1):
                tables = page.extract_tables()
                for table_number, table in enumerate(tables, start=1):
                    df = pd.DataFrame(table[1:], columns=table[0])
                    data = pd.concat([data, df], ignore_index=True)
        return data

    @staticmethod    
    def read_file(file_path:str):
        file_path = Path(file_path)
        if file_path.suffix == '.pdf':
            df = FileHanding.read_pdf(file_path)
        if file_path.suffix == '.xlsx':
            df = pd.read_excel(file_path)
        
        df = FileHanding.dataframe_handler(df)
        return df

    @staticmethod    
    def search_file(directory: str, filename: str):
        directory = Path(directory)
        """在指定目录中搜索文件"""
        for root, dirs, files in os.walk(directory):
            print(files)
            for file in files:
                if FileHanding.remove_suffix(file) == filename:
                    return os.path.join(root, file)
        return None

    @staticmethod
    def remove_suffix(filename: str) -> str:
        """去掉文件名的后缀"""
        return os.path.splitext(filename)[0]
        
    # @staticmethod    
    # def revise_value_of_df(df: pd.DataFrame):
    #     columns = df.columns.tolist()
    #     df[columns[1]] = df[columns[1]].apply(lambda x: x.rsplit('-', 1)[0] if isinstance(x, str) else x)
    #     return df
